package com.haian.slidealbum.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.gmail.yuyang226.flickr.oauth.OAuth;
import com.gmail.yuyang226.flickr.oauth.OAuthToken;
import com.gmail.yuyang226.flickr.people.User;
import com.haian.slidealbum.R;
import com.haian.slidealbum.common.ConstCommon;
import com.haian.slidealbum.model.adapter.AdapterFlickrAlbum;
import com.haian.slidealbum.model.delegate.ServiceDelegate;
import com.haian.slidealbum.model.delegate.flickrplugin.GetOAuthTokenTask;
import com.haian.slidealbum.model.delegate.flickrplugin.OAuthTask;
import com.haian.slidealbum.model.object.ObjectFlickrAlbum;
import com.haian.slidealbum.model.object.ObjectFlickrImage;

public class FlickrAlbumActivity extends Activity {

	public static boolean KEY_FOR_RESUM_ALBUM = false;
	public static int KEY_ID_RESUM_ALBUM = 0;
	
	GridView gridContent;
	AdapterFlickrAlbum adapter;
	ArrayList<ObjectFlickrAlbum> arrayAlbum;
	ArrayList<ObjectFlickrImage> arrayImage;
	Context mContext;
	int CREATE_NEW_ALBUM = 1, UPDATE_ALBUM = 2;
	String KEY_FROM_WHERE;
	int KEY_ID_ALBUM;

	int LOADING = 0, CONTENT = 1, ERRO = 2;
	ViewFlipper vf;
	ProgressBar progressBar;
	String user_id;

	// for Flickr
	public static final String CALLBACK_SCHEME = "flickrj-android-oauth";
	public static final String PREFS_NAME = "flickrj-android-pref";
	public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken";
	public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret";
	public static final String KEY_USER_NAME = "flickrj-android-userName";
	public static final String KEY_USER_ID = "flickrj-android-userId";

	// __________________________ System Function

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_flickr_album);
		initDB();
		initWidget();
		loginToFlickr();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == UPDATE_ALBUM) {
			if (resultCode == RESULT_OK) {
				try {
					Intent returnIntent = new Intent();
					int mResultIdAlbum = data.getIntExtra(
							ConstCommon.KEY_RESULT_ID_ALBUM, 0);
					returnIntent.putExtra(ConstCommon.KEY_RESULT_ID_ALBUM,
							String.valueOf(mResultIdAlbum));
					setResult(RESULT_OK, returnIntent);
					KEY_FOR_RESUM_ALBUM = true;
					KEY_ID_RESUM_ALBUM = mResultIdAlbum;
				} catch (Exception e) {
					// TODO: handle exception
				}
				finish();
			}
		}
	}

	void initDB() {
		mContext = this;
		arrayAlbum = new ArrayList<ObjectFlickrAlbum>();
		KEY_FOR_RESUM_ALBUM = false;
		KEY_ID_RESUM_ALBUM = 0;
	}

	void initWidget() {
		vf = (ViewFlipper) findViewById(R.id.vf);
		vf.setDisplayedChild(LOADING);
	}

	public void loginToFlickr() {
		try {
			OAuth oauth = getOAuthToken();
			if (oauth == null || oauth.getUser() == null) {
				OAuthTask task = new OAuthTask(mContext);
				task.execute();
			} else {
				user_id = oauth.getUser().getId();
				if (user_id.equals("") == false) {
					ServiceDelegate.getFlickrAlbum(mhandlerAlbum, user_id);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	Handler mhandlerAlbum = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;
					String status = dataJSONObject
							.getString(ServiceDelegate.KEY_STAT);
					if (status.equals("ok")) {
						JSONObject photosetsJSONObject = new JSONObject();
						photosetsJSONObject = dataJSONObject
								.getJSONObject(ServiceDelegate.KEY_PHOTOSETS);

						JSONArray photosetJSONArray = new JSONArray();
						photosetJSONArray = photosetsJSONObject
								.getJSONArray(ServiceDelegate.KEY_PHONESET);
						if (photosetJSONArray.length() > 0) {
							arrayAlbum = new ArrayList<ObjectFlickrAlbum>();
							for (int i = 0; i < photosetJSONArray.length(); i++) {
								JSONObject albumJSONObject = new JSONObject();
								albumJSONObject = photosetJSONArray
										.getJSONObject(i);
								int totalImgOfAlbum = albumJSONObject
										.getInt(ServiceDelegate.KEY_TOTAL_PHOTOS);
								if (totalImgOfAlbum > 0) {
									ObjectFlickrAlbum mObjectFlickrAlbum = new ObjectFlickrAlbum();
									mObjectFlickrAlbum
											.setTotalImg(totalImgOfAlbum);
									mObjectFlickrAlbum
											.setAlbum_id(albumJSONObject
													.getString(ServiceDelegate.KEY_ID));
									JSONObject titleJSONObject = new JSONObject();
									titleJSONObject = albumJSONObject
											.getJSONObject(ServiceDelegate.KEY_TITLE);
									mObjectFlickrAlbum
											.setAlbum_name(titleJSONObject
													.getString(ServiceDelegate.KEY_CONTENT));
									arrayAlbum.add(mObjectFlickrAlbum);
								}
							}
							if (arrayAlbum.size() > 0) {
								vf.setDisplayedChild(CONTENT);
								gridContent = (GridView) vf
										.findViewById(R.id.gridContent);
								gridContent.setFastScrollEnabled(true);
								adapter = new AdapterFlickrAlbum(
										FlickrAlbumActivity.this, arrayAlbum);
								gridContent.setAdapter(adapter);
								gridContent
										.setOnItemClickListener(new OnItemClickListener() {

											@Override
											public void onItemClick(
													AdapterView<?> parent,
													View view, int position,
													long id) {
												Intent intent = new Intent(
														mContext,
														FlickrImageAddActivity.class);
												intent.putExtra(
														ConstCommon.KEY_RESULT_ID_ALBUM,
														arrayAlbum
																.get(position)
																.getAlbum_id());
												intent.putExtra(
														ServiceDelegate.KEY_ACCESS_TOKEN,
														user_id);
												startActivityForResult(intent,
														UPDATE_ALBUM);
											}
										});
							} else {
								vf.setDisplayedChild(ERRO);
							}
						} else {
							vf.setDisplayedChild(ERRO);
						}
					} else {
						vf.setDisplayedChild(ERRO);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	};

	// _____________________ Method for login

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
	}

	@Override
	public void onResume() {
		super.onResume();
		try {
			Intent intent = getIntent();
			String scheme = intent.getScheme();
			OAuth savedToken = getOAuthToken();
			if (CALLBACK_SCHEME.equals(scheme)
					&& (savedToken == null || savedToken.getUser() == null)) {
				Uri uri = intent.getData();
				String query = uri.getQuery();
				String[] data = query.split("&"); //$NON-NLS-1$
				if (data != null && data.length == 2) {
					String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
					String oauthVerifier = data[1]
							.substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
					OAuth oauth = getOAuthToken();
					if (oauth != null && oauth.getToken() != null
							&& oauth.getToken().getOauthTokenSecret() != null) {
						GetOAuthTokenTask task = new GetOAuthTokenTask(
								FlickrAlbumActivity.this);
						task.execute(oauthToken, oauth.getToken()
								.getOauthTokenSecret(), oauthVerifier);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void onOAuthDone(OAuth result) {
		if (result == null) {
			Toast.makeText(
					this,
					mContext.getResources().getString(
							R.string.login_failed_please_try_again),
					Toast.LENGTH_LONG).show();
		} else {
			try {
				User user = result.getUser();
				OAuthToken token = result.getToken();
				if (user == null || user.getId() == null || token == null
						|| token.getOauthToken() == null
						|| token.getOauthTokenSecret() == null) {
					Toast.makeText(
							this,
							mContext.getResources().getString(
									R.string.login_failed_please_try_again),
							Toast.LENGTH_LONG).show();
					return;
				}
				saveOAuthToken(user.getUsername(), user.getId(),
						token.getOauthToken(), token.getOauthTokenSecret());

				String user_id = user.getId();
				ServiceDelegate.getFlickrAlbum(mhandlerAlbum, user_id);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public OAuth getOAuthToken() {
		OAuth oauth = new OAuth();
		try {
			SharedPreferences settings = getSharedPreferences(PREFS_NAME,
					Context.MODE_PRIVATE);
			String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
			String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
			if (oauthTokenString == null && tokenSecret == null) {
				return null;
			}
			
			String userName = settings.getString(KEY_USER_NAME, null);
			String userId = settings.getString(KEY_USER_ID, null);
			if (userId != null) {
				User user = new User();
				user.setUsername(userName);
				user.setId(userId);
				oauth.setUser(user);
			}
			OAuthToken oauthToken = new OAuthToken();
			oauth.setToken(oauthToken);
			oauthToken.setOauthToken(oauthTokenString);
			oauthToken.setOauthTokenSecret(tokenSecret);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return oauth;
	}

	public void saveOAuthToken(String userName, String userId, String token,
			String tokenSecret) {
		try {
			SharedPreferences sp = getSharedPreferences(PREFS_NAME,
					Context.MODE_PRIVATE);
			Editor editor = sp.edit();
			editor.putString(KEY_OAUTH_TOKEN, token);
			editor.putString(KEY_TOKEN_SECRET, tokenSecret);
			editor.putString(KEY_USER_NAME, userName);
			editor.putString(KEY_USER_ID, userId);
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
